package dice.sinanya.db.npclist;

import dice.sinanya.db.tools.DbUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.HashMap;

import static dice.sinanya.system.NpcListCache.NPC_LIST;
import static dice.sinanya.tools.makedata.MakeProperties.makeProMapToStr;
import static dice.sinanya.tools.makedata.MakeProperties.makeProStrToMap;

public class InsertNpcList {
    private static final Logger log = LogManager.getLogger(InsertNpcList.class.getName());


    public InsertNpcList() {
        //        初始化时不需要参数
    }

    public void insertNpcList(String groupId, String name, String properties) {
        try (Connection conn = DbUtil.getConnection()) {
            String sql = "REPLACE INTO test.npcList(" +
                    "groupId, name,properties) VALUES(?,?,?)";
            try (PreparedStatement ps = conn.prepareStatement(sql)) {
                ps.setString(1, groupId);
                ps.setString(2, name);
                ps.setString(3, properties);
                ps.executeUpdate();
            }
            HashMap<String, HashMap<String, Integer>> NPC_TMP = NPC_LIST.getOrDefault(groupId, new HashMap<>());
            NPC_TMP.put(name, makeProStrToMap(properties));
            NPC_LIST.put(groupId, NPC_TMP);
        } catch (SQLException e) {
            log.error(e.getMessage(), e);
        }
    }

    public void insertNpcList(String groupId, String name, HashMap<String, Integer> properties) {
        insertNpcList(groupId, name, makeProMapToStr(properties));
    }

    public void deleteNpcList(String groupId, String name) {
        try (Connection conn = DbUtil.getConnection()) {
            String sql = "delete from test.npcList where groupId=? and name=?";
            try (PreparedStatement ps = conn.prepareStatement(sql)) {
                ps.setString(1, groupId);
                ps.setString(2, name);
                ps.executeUpdate();
            }
            HashMap<String, HashMap<String, Integer>> NPC_TMP = NPC_LIST.getOrDefault(groupId, new HashMap<>());
            NPC_TMP.remove(name);
            NPC_LIST.put(groupId, NPC_TMP);
        } catch (SQLException e) {
            log.error(e.getMessage(), e);
        }
    }

    public void deleteNpcListByGroup(String groupId) {
        try (Connection conn = DbUtil.getConnection()) {
            String sql = "delete from test.npcList where groupId=?";
            try (PreparedStatement ps = conn.prepareStatement(sql)) {
                ps.setString(1, groupId);
                ps.executeUpdate();
            }
            NPC_LIST.remove(groupId);
        } catch (SQLException e) {
            log.error(e.getMessage(), e);
        }
    }
}

